<template>
  <div class="loginBG" >
    <div :class="type === 'login' ? 'loginCenter' : 'loginCenter enrollCenter'">
      <div class="timeArea">
        <img src="http://wxpro.xlmediawatch.com/img/inews促销活动/元素/注册登录/路径4.png" alt="">
        <span class="timeDu">活动时间：{{timeDu}}</span>
      </div>
      <div class="loginArea">
        <section class="title">
          <span>{{
              type === 'login' ? '登录'
                  : type === 'enroll' ? '欢迎注册'
                      : ''
            }}</span>
          <span> iNEWS</span>
        </section>
        <section class="rules" :style="type === 'enroll' ? 'margin-bottom: 0' : ''">
          <span @click="useDes" style="cursor: pointer">规则</span>
          <span>{{ '>' }}</span>
        </section>
        <section class="userArea" :style="type === 'enroll' ? 'padding-top: 0' : ''">
          <div v-if="type === 'enroll'" style="margin-top: 0">
            <div class="everyMsg">
              <span class="labels">
              公司名称
              </span>
              <input type="text" v-model="data.comNumber">
            </div>
            <div class="message">
              <span v-show="data.notCom">请输入公司名称</span>
            </div>
          </div>
          <div>
            <div class="everyMsg">
              <span class="labels">
              手机号
              </span>
              <input ref="InputF" id="InputF" type="text" v-model="data.phoneNumber">
            </div>
            <div class="message">
              <span v-show="data.notPhone">请输入手机号</span>
            </div>
          </div>
          <div>
            <div class="everyMsg">
              <span class="labels">
              验证码
              </span>
              <input type="text"  v-model="data.codeNumber" style="width: calc(100% - 150px)">
              <button style="float: right" class="verifyBtn" :style="showTime === true ? 'cursor: not-allowed' : ''" @click="getCode">{{ showTime === true ? timeNum : '点击获取' }}</button>
            </div>
            <div class="message">
              <span  v-show="data.notCode">请输入验证码</span>
            </div>
          </div>
        </section>
        <section class="article">
          <input type="checkbox" v-model="data.agree">
          <span style="font-size: 12px">我已阅读并同意新联财通的<span style="color: #5f58d2;cursor: pointer" @click="openPrivacy">隐私政策</span>和<span
              style="color: #5f58d2;cursor: pointer" @click="useDes">使用条款</span></span>
        </section>
        <section class="loginBtn">
          <button class="login" @click="loginOrEnroll">{{
              type === 'login' ? '登录'
                  : type === 'enroll' ? '注册并领券'
                      : ''
            }}
          </button>
          <button class="enroll" @click="goEnroll">{{
              type === 'login' ? '注册新用户'
                  : type === 'enroll' ? '已有账号登录'
                      : ''
            }}
          </button>
        </section>
      </div>
    </div>
    <div class="modal" v-if="showModal"></div>
  </div>

<!--   隐私协议-->
  <el-drawer
      v-model="drawer"
      title="隐私协议"
      :direction="direction"
      :with-header="false"
      :size="'90vh'"
  >
    <div>
      <header style="text-align: center;font-weight: 700">隐私政策</header>
      <p style="font-size: 12px" v-html="text.privacyAgreement"></p>
    </div>
  </el-drawer>
  <el-drawer
      v-model="desDrawer"
      title="活动规则"
      :direction="direction"
      :with-header="false"
      :size="'90vh'"
  >
    <div>
      <header style="text-align: center;font-weight: 700">活动规则</header>
      <p style="font-size: 12px" v-html="text.termsOfUse"></p>
    </div>
  </el-drawer>

</template>


<script lang="ts">

import axios from "axios";
import {ref,reactive,defineComponent ,h, onUpdated, onMounted} from 'vue'
import 'element-plus/es/components/button/style/css'
import {useRouter,useRoute} from "vue-router";
import {getAuthCode, getEnrollAuthCode, userInfo} from "../../../../api/api"
import Cookies from 'js-cookie';
import {textObj} from "../../../../assets/text";
import wx from "weixin-js-sdk";

export default defineComponent({
  beforeRouteLeave (to, from, next) {
    console.log('to',to.href)
    if(to.href.indexOf('/salesPromotion/loginBefore') !== -1){
      document.getElementsByTagName('body')[0].setAttribute('class','leaveModal')
      setTimeout(() => {
        // 这里需要elementui的支持，如果使用其他界面组件自行替换即可
        ElMessageBox.confirm( '',{
          message:h('div',{
            class:'leaveArea',
            style:{
              textAlign:'center'
            }
          }, [
            h('div',{ style:'color:black;font-weight:700;margin-bottom:10px;font-size:12px' },'要放弃iNEWS舆情平台会员权益吗？'),
            h('div',{ style:'color:#d2110c;font-weight:700;font-size:12px;margin-bottom:4px;-webkit-transform: scale(0.9)' },'开通账号可享受7天免费试用'),
            h('div',{ style:'color:#d2110c;font-weight:700;font-size:12px;-webkit-transform: scale(0.9)' },'并领取4000+现金减免券')
          ]),
          cancelButtonText: '继续看看',
          confirmButtonText: '残忍离开',
          customClass:'del-model',
          closeOnClickModal:false,
          closeOnPressEscape:false,
        }).then(() => {
          // 正常跳转
          wx.closeWindow()
          document.getElementsByTagName('body')[0].classList.remove('leaveModal')
        }).catch(() => {
          // 如果取消跳转地址栏会变化，这时保持地址栏不变
          window.history.go(1)
        })
      }, 100);
    }else{
      next()
    }

  },
  setup(){

    const data = reactive({
      phoneNumber: ref<string>(''),
      codeNumber:ref<string>(''),
      comNumber:ref<string>(''),
      notPhone:ref<boolean>(false),
      notCode:ref<boolean>(false),
      notCom:ref<boolean>(false),
      agree:ref<boolean>(false),
    })

    const InputF = ref<any>(null)

    onMounted(() => {
      // console.log('InputF',InputF.value)
      // InputF.value.focus()
    })

    /**
     * 获取微信签名
     */
    const  getSignature = async() => {
      // let url = location.href.split("#")[0];
      let url = window.location.origin;
      // let url = 'http://process.xlmediawatch.com';
      try {
        // await this.wechatStart()
        await getAjax('get', `http://59.110.22.117/wechat/sign?url=${url}`, '', '新联年底大促')

      } catch (e) {
        console.log(e);
      }
    }

    /**
     * 封装ajax
     * @param _methods 调用请求  post  get 。。。
     * @param url  请求地址
     * @param _data  请求参数
     * @param desc  描述
     */
    const getAjax = (_methods:string, url:string, _data:any,desc:any) => {
      return new Promise((resolve, reject) => {
        let xhr: XMLHttpRequest;
        if (XMLHttpRequest) {
          xhr = new XMLHttpRequest()
        } else {
          xhr = new ActiveXObject()
        }
        let data = _data || null;
        let methods = _methods || 'get';
        xhr.open(methods, url, true)
        // 设置请求头
        // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send(data)
        xhr.onreadystatechange = () => {
          if(xhr.readyState === 4){
            let result = xhr.responseText
            getWxConfig(JSON.parse(result),desc)
          }


        }
      })
    }

    /**
     * 微信jssdk注册
     * @param result  接口返回的签名等参数
     * @param desc  描述
     */
    const getWxConfig = (result:any,desc:any) => {
      wx.config({
        debug: false, // true时，手机微信环境访问会alert一些errmsg信息，如果显示errmsg:ok表示正常，否认表示出了问题
        appId: result.appId, // 必填，公众号的唯一标识
        timestamp: result.timestamp, // 后台返回的数据中取
        nonceStr: result.nonceStr, // 后台返回的数据中取
        signature: result.signature, // 后台返回的数据中取
        jsApiList: [
          'checkJsApi',
          'onMenuShareAppMessage',
          'onMenuShareTimeline',
          'updateAppMessageShareData',
          'updateTimelineShareData',
          'closeWindow'
        ]
      })
      wx.ready(function() {
        let link:string = ''
        if(window.location.href.indexOf('?') !== -1){
          link = window.location.href.split('?')[0]
        }else{
          link = window.location.href
        }
        // 0: "onMenuShareAppMessage"
        // 1: "onMenuShareTimeline"
        // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
        wx.onMenuShareAppMessage({
          title: '新联年底大促', // 分享标题
          desc: String(desc), // 分享描述
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: 'http://wxpro.xlmediawatch.com/img/inews促销活动/hot_share_logo.png', // 分享图标
          success: function() {
            // 设置成功
          },
          fail: function () {
          }
        })
        // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
        wx.onMenuShareTimeline({
          title: '新联年底大促', // 分享标题
          desc: String(desc), // 分享描述
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: 'http://wxpro.xlmediawatch.com/img/inews促销活动/hot_share_logo.png', // 分享图标
          success: function() {
            // 设置成功
          },
          fail: function () {
          }
        })
        // wx.closeWindow();
      })
    }


    /**
     * 调用获取微信签名
     */
    getSignature()


    const timeDu:string = '2022年12月12日-12月31日'
    const drawer = ref(false)
    const desDrawer = ref(false)
// 抽屉方向
    const direction = ref('btt')




    const text:object = textObj
    const timeNum = ref<number>(59)
    const showTime = ref<boolean>(false)
    let timer:any = null


    let router = useRouter();
    const showModal = ref<boolean>(false)
    const type = ref<string>('login')
    const goEnroll = () => {
      if (type.value === 'login') {
        type.value = 'enroll'
      } else {
        type.value = 'login'
      }
      data.notPhone = false
      data.notCode = false
      data.notCom = false
      showTime.value = false
      clearInterval(timer)
      timeNum.value = 59
    }

    /**
     * 获取验证码
     */
    const getCode = async() => {
      let reg = new RegExp(/^1(\d{10})$/);
      if(!(reg.test(data.phoneNumber))) {
        ElMessage({
          message: '请输入正确手机号',
          type: 'error',
        })
        return;
      }
      if(showTime.value === true){
        return
      }
      showTime.value = true
      timer = setInterval(() => {
        timeNum.value--
        if(timeNum.value === 0){
          showTime.value = false
          clearInterval(timer)
          timeNum.value = 59
        }
      },1000)
      try {
        let result
        if(type.value === 'login'){
          result = await getAuthCode(data.phoneNumber)
        }
        else{
          // 注册
          result = await getEnrollAuthCode(data.phoneNumber)
        }
        console.log('result',result)
        if(result.data.status === 0){
          ElMessage({
            message: '验证码已发送，请注意查收',
            type: 'success',
          })
        }else{
          ElMessage({
            message: result.data.msg,
            type: 'error',
          })
          showTime.value = false
          clearInterval(timer)
          timeNum.value = 59
        }
      }catch (e) {
        console.error(e)
        ElMessage({
          message: '验证码发送失败，请稍后重试',
          type: 'error',
        })
        showTime.value = false
        clearInterval(timer)
        timeNum.value = 59
      }

    }
    const loginLoading = ref<boolean>(false)
    /**
     * 登录和注册
     */
    const loginOrEnroll = async() => {
      if(data.agree === false){
        ElMessage.warning("请先确认隐私协议和使用条款")
        return
      }
      data.notPhone = data.phoneNumber === '';
      data.notCode = data.codeNumber === '';
      data.notCom = data.comNumber === '';
      if(type.value === 'login' && (data.notPhone || data.notCode)){
        // 登录
        return
      }else if(type.value === 'enroll' && (data.notPhone || data.notCode || data.notCom)){
        //  注册
        return
      }
      if(loginLoading.value === true){
        return
      }
      const loading = ElLoading.service({
        lock: true,
        text: '请稍后...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      loginLoading.value = true
      try {
        // 登录
        if(type.value === 'login'){
          if(data.codeNumber.substr(0, 1) != "p" ) {
            axios.get(`http://api.xlmediawatch.com/INEWSAPI/api/vcode/verify/${data.phoneNumber}/${data.codeNumber}`).then( function(res) { // 22.7.11注释更换阿里云
              if(res.data.status == 0) {
                if(res.data.data == 1) {
                  const params = new URLSearchParams();
                  const client_id=window.location.hostname;
                  params.append('client_id', client_id);
                  params.append('grant_type', "password");
                  params.append('username', data.phoneNumber);
                  params.append("password", data.codeNumber);
                  axios.post('http://u.xlmediawatch.com/auth/realms/xlplatform/protocol/openid-connect/token',params,
                      {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then( async function (res) {
                    //Cookies.set('permission', res.data["access_token"]);
                    let millisecond = new Date().getTime();
                    let expiresTime = new Date(millisecond + 60 * 1000 * 15);
                    Cookies.set('refreshToken', res.data["refresh_token"], {
                      expires: expiresTime,
                    });
                    let resultUser = await userInfo()
                    console.log(resultUser)
                    if (resultUser.data.status === 0) {
                      sessionStorage.setItem('userInfo', resultUser.data.data)
                      clearInterval(timer)
                      loginLoading.value = false
                      loading.close()
                      router.push({path:"/salesPromotion/user"});

                    }
                  }).catch(function (error) { // 请求失败处理
                    console.error(error)
                    loginLoading.value = false
                    loading.close()
                    ElMessage.error("帐号信息错误")
                  });
                } else {
                  loginLoading.value = false
                  loading.close()
                  ElMessage.error("验证码错误")
                }
              } else {
                loginLoading.value = false
                loading.close()
                ElMessage.error(res.data.msg)
              }
            }).catch(function (error) { // 请求失败处理
              console.error(error)
              loginLoading.value = false
              loading.close()
              ElMessage.error("帐号信息错误")
            });
          } else {
            const params = new URLSearchParams();
            const client_id=window.location.hostname;
            params.append('client_id', client_id);
            params.append('grant_type', "password");
            params.append('username', data.phoneNumber);
            params.append("password", data.codeNumber.substr(1));
            axios.post('http://u.xlmediawatch.com/auth/realms/xlplatform/protocol/openid-connect/token',params,
                {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then( async function (res) {
              let millisecond = new Date().getTime();
              let expiresTime = new Date(millisecond + 60 * 1000 * 15);
              Cookies.set('refreshToken', res.data["refresh_token"], {
                expires: expiresTime,
              });
              let resultUser = await userInfo()
              if(resultUser.data.status === 0){
                sessionStorage.setItem('userInfo',resultUser.data.data)
                clearInterval(timer)
                loginLoading.value = false
                loading.close()
                router.push({path:"/salesPromotion/user"});
              }
            }).catch(function (error) { // 请求失败处理
              console.log(error);
              loginLoading.value = false
              loading.close()
              ElMessage.error("帐号信息错误")
            });
          }
        }
        // 注册
        else if(type.value === 'enroll'){
          let str:string = String(new Date().valueOf())
          const body = {
            phone: data.phoneNumber,
            vcode: data.codeNumber,
            password: '123456',
            nickName:data.comNumber,
            // nickName:'微信用户' + str.substring(str.length-8, str.length),
            corp: data.comNumber
          }
          console.log('body',body)
          axios.post(`http://api.xlmediawatch.com/INEWSAPI/api/register/phone`,body
          ).then( function(res) {
            console.log('res',res)
            if(res.data.status == 0) {
              loginLoading.value = false
              loading.close()
              ElMessage.success('注册成功，请前往登录页面进行登录！');
              type.value = 'login'
              showTime.value = false
              clearInterval(timer)
              timeNum.value = 59
              // that.flag = false;
              // that.$Message.success(that.$t('createdMsg'));
              // that.$router.push({
              //   path: "/login",
              // })
              // sessionStorage.setItem("register","1");
            } else {
              loginLoading.value = false
              loading.close()
              showTime.value = false
              clearInterval(timer)
              timeNum.value = 59
              // this.flag = false;
              ElMessage.error(res.data.msg);
            }
          }).catch(function (error) { // 请求失败处理
            loginLoading.value = false
            loading.close()
            showTime.value = false
            clearInterval(timer)
            timeNum.value = 59
          });
        }

      }catch (e) {
        console.error(e)
        loginLoading.value = false
        loading.close()
      }
    }

    /**
     * 打开隐私协议
     */
    const openPrivacy = () => {
      drawer.value = true
    }

    /**
     * 规则
     */
    const useDes = () => {
      desDrawer.value = true
    }

    return {
      showTime,
      data,
      timeDu,
      drawer,
      desDrawer,
      direction,
      text,
      showModal,
      type,
      goEnroll,
      getCode,
      loginOrEnroll,
      openPrivacy,
      useDes,
      timeNum,
      loginLoading
    }
  },

})



</script>
<style lang="scss">
.leaveModal {
  .el-message-box__close {
    display: none;
  }

  .el-message-box.del-model {
    background: transparent;
    border: none;
    box-shadow: none;
    position: relative;
    width: 300px;
.el-message-box__header{
  display: none;
}
    .el-message-box__btns {
      padding: 0;
      position: absolute;
      top: 52%;
      left: 40px;
      flex-direction : row-reverse;
      width: 74%;
      flex-shrink: 0;
      justify-content: space-around;
      > button {
        font-size: 12px;
        height: 24px !important;
        border-radius: 8px;
        padding: 0 18px;
      }

      > button:nth-child(1) {
        background: #d10c02 !important;
        color: white;
      }

      > button:nth-child(2) {
        background: #252524;
        color: white;
        margin-left: 0;
      }
    }
  }
}

.leaveArea {
  max-width: 390px;
  background: url("http://wxpro.xlmediawatch.com/img/inews促销活动/元素/挽留页/leaveBG.png") no-repeat;
  background-size: 100%;
  height: 407px;
  >div:nth-child(1){
    display: flex;
    justify-content: center;
    padding-top: 50%;
  }
  >div:nth-child(2){
    display: flex;
    justify-content: center;
    padding-top: 1%;
  }
  >div:nth-child(3){
    display: flex;
    justify-content: center;
    padding-top: 1%;
  }
}

.loginBG {
  height: 100vh;
  overflow: hidden;
  background: red;
  .loginCenter {
    margin: auto;
    //width: 100vw;
    height: 100vh;
    background: url("http://wxpro.xlmediawatch.com/img/inews促销活动/元素/注册登录/loginBG.jpg") no-repeat;
    background-size: 100% 100%;


    .timeArea {
      text-align: center;
      padding-top: 15vh;
      margin-bottom: 10px;
      position: relative;
      > img {
      }
      .timeDu{
        position: absolute;
        bottom: 20px;
        left: calc(50% - 120px);
        color: white;
        font-size: 14px;
        transform: rotate(-5deg); /* Equal to rotateZ(45deg) */
      }
    }

    .loginArea {
      border-radius: 16px;
      margin: auto;
      width: 90%;
      max-width: 600px;
      max-height: 50vh;
      min-height: 327px;
      background: #fff;
      padding: 24px;
      box-sizing: border-box;
      display: flex;
      flex-wrap: wrap;

      .title {
        > span:nth-child(1) {
          font-size: 28px;
          font-weight: 700;
          color: #1f1f1f;
        }

        > span:nth-child(2) {
          font-size: 26px;
          color: #fc5c02;
          font-weight: 700;
          //font-family:;
        }
      }

      .rules {
        //display: flex;
        //align-items: center;
        //justify-content: right;
        text-align: right;
        margin-bottom: 0.5vh;

        > span:nth-child(1) {
          font-size: 14px;
          font-weight: 700;
          color: #5e5e5e;
          cursor: pointer;
          margin-right: 2px;
        }

        > span:nth-child(2) {
          font-size: 16px;
          color: #7b7b7b;
          cursor: pointer;
          //font-weight: 700;
          //font-family:;
        }
      }

      .userArea {
        padding: 6px 0;

        > div {
          margin-top: 0.5vh;

          .everyMsg {
            border-bottom: 1px solid #f1eff0;

            .labels {
              color: #393939;
              font-weight: 700;
              font-size: 14px;
            }

            input {
              border: none;
              width: calc(100% - 70px);
              background: #fff;
              outline: none;
            }

            .verifyBtn {
              width: 64px;
              height: 20px;
              cursor: pointer;
              outline: none;
              border: none;
              border-radius: 4px;
              color: #fff;
              padding: 2px 8px;
              background: #c10101;
              font-size: 10px;
            }

            .verifyBtn:hover {
              background: rgba(193, 1, 1, 0.6);
            }
          }

          .message {
            color: red;
            padding-left: 50px;
            font-size: 12px;
            display: block;
            height: 24px;
          }
        }
      }

      .article {
        margin-top: 1px;
        display: flex;
        align-items: center;
        font-size: 10px;

        input {
          height: 13px;
          width: 13px;
          margin-right: 6px;
          margin-top: 2px;
        }
      }

      .loginBtn {
        margin-top: 4vh;

        button {
          height: 4vh;
          min-height: 26px;
          text-align: center;
          line-height: 100%;
          cursor: pointer;
          width: 100%;
          border: none;
          outline: none;
          border-radius: 6px;
          margin-bottom: 0.5vh;
        }

        .login {
          color: #fff;
          background: #c10101;
        }

        .login:hover {
          background: rgba(193, 1, 1, 0.6);
        }

        .enroll {
          background: #fff;
          color: #2c2c2c;
          font-weight: 700;
        }
      }

      >section{
        width: 100%;
      }
    }
  }
  .enrollCenter{
    margin: auto;
    //width: 100vw;
    height: 100%;
    background: url("http://wxpro.xlmediawatch.com/img/inews促销活动/元素/注册登录/fcb9cf899d9c4bfc352e9d61cfe2d266.png") no-repeat,url("http://wxpro.xlmediawatch.com/img/inews促销活动/元素/注册登录/loginBG.jpg") no-repeat;
    background-size: 100% 100%;

  }
  .modal {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(70, 68, 68, 0.5);
  }
}
</style>
